//
//  LiaoTianWenJianChaKanViewController.m
//  faYunTong
//
//  Created by iMac on 2023/9/6.
//  Copyright © 2023 iningKe. All rights reserved.
//

#import "LiaoTianWenJianChaKanViewController.h"
         
#import <WebKit/WebKit.h>

#import "ZBNetworking.h"

@interface LiaoTianWenJianChaKanViewController ()
//<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>
{
    NSString *localPath;
}

@property (weak, nonatomic) IBOutlet WKWebView *mainWebView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@end

@implementation LiaoTianWenJianChaKanViewController


//
//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.mainWebView.configuration.userContentController addScriptMessageHandler:self name:@"buttonClick"];
//    
//    self.navigationController.navigationBar.hidden = YES;
//
//}
//
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.mainWebView.configuration.userContentController removeScriptMessageHandlerForName:@"buttonClick"];
//
//}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    if (@available(iOS 11.0, *)) {
        self.mainWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.topSpace.constant = NavaBarHeight;
//    
//    _mainWebView.UIDelegate = self;
//    _mainWebView.navigationDelegate = self;
    
    self.customNavBar.title = @"预览";
    [[ZZPRequest getWebUtil] addAnimation];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest * request) {
         request.url =  _loadUrl;
         request.methodType=ZBMethodTypeDownLoad;
         request.downloadState=ZBDownloadStateStart;//开始 //ZBDownloadStateStop暂停
     } progress:^(NSProgress * _Nullable progress) {
         NSLog(@"onProgress: %.2f", 100.f * progress.completedUnitCount/progress.totalUnitCount);
     } success:^(id  responseObject,ZBURLRequest * request) {
         
         
         [[ZZPRequest getWebUtil] hiddenAnimation];
         
         NSLog(@"ZBMethodTypeDownLoad 此时会返回存储路径文件: %@", responseObject);
          //在任何地方拿到下载文件
         NSString *file=[ZBRequestManager getDownloadFileForKey:request.url];
  
         NSLog(@"file:%@",file)
         
         
         [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"跟进记录更多")];
         
         self.customNavBar.onClickRightButton = ^{
             UIActivityViewController *activityVC =
                 [[UIActivityViewController alloc] initWithActivityItems:@[[NSURL fileURLWithPath:file]]
                                                   applicationActivities:nil];
             UIPopoverPresentationController *popPresenter = [activityVC popoverPresentationController];
             UIWindow *window = [UIApplication sharedApplication].keyWindow;
             popPresenter.sourceView = window;
             popPresenter.sourceRect = CGRectMake(window.frame.size.width / 2, window.frame.size.height / 2, 0, 0);
             popPresenter.permittedArrowDirections = 0;
             [self presentViewController:activityVC animated:YES completion:nil];
         };
         
         dispatch_async(dispatch_get_main_queue(), ^{
             [_mainWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:file]]];
         });
    
     } failure:^(NSError * _Nullable error) {
         NSLog(@"error: %@", error);
         
         [[ZZPRequest getWebUtil] hiddenAnimation];
     }];
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self.mainWebView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'"
                             completionHandler:nil];
    [self.mainWebView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'"
                             completionHandler:nil];
}

- (void)webView:(WKWebView *)webView
    didFailNavigation:(null_unspecified WKNavigation *)navigation
            withError:(NSError *)error {
    [ZZPUtils showWarning:@"加载失败"];
}

- (void)webView:(WKWebView *)webView
    didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation
                       withError:(NSError *)error {
    NSLog(@"error:%@",error);
}

- (void)webView:(WKWebView *)webView
    didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
                    completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
                                                NSURLCredential *_Nullable credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, card);
        });
    }
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
